<?php

namespace app\librarys;


use yii\helpers\Url;
use yii\web\UrlManager;

class Tools
{
    /**
     * 获取当前系统时间(精确到毫秒)
     * @return float
     */
    public static function getMillisecond()
    {
        list($t1, $t2) = explode(' ', microtime());
        return (float)sprintf('%.0f', (floatval($t1) + floatval($t2)) * 1000);
    }

    /**
     * 获取当前系统时间(精确到微秒)
     * @return float
     */
    public static function getMicrosecond()
    {
        list($t1, $t2) = explode(' ', microtime());
        return (float)sprintf('%.0f', (floatval($t1) + floatval($t2)) * 1000000);
    }

    public static function postJson($url, $data, $JSON_UNESCAPED_UNICODE = false)
    {
        if ($JSON_UNESCAPED_UNICODE) {
            $data_string = json_encode($data, JSON_UNESCAPED_UNICODE);
        } else {
            $data_string = json_encode($data);
        }
        $ch = curl_init($url);
        //https 请求
        if (strlen($url) > 5 && strtolower(substr($url, 0, 5)) == 'https') {
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        }

        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                'Content-Type: application/json',
                'Content-Length: ' . strlen($data_string),
                'charset=utf-8',)

        );

        $result = curl_exec($ch);
        return $result;
    }


    /*
* 实现AES加密
* $str : 要加密的字符串
* $keys : 加密密钥
* $iv : 加密向量
* $cipher_alg : 加密方式
*/
   public static function ecryptdString($str,$keys="xintai22eac4488ca3143chinalifecq",$iv="8105547186756005",$cipher_alg=MCRYPT_RIJNDAEL_128){
        $encrypted_string = bin2hex(mcrypt_encrypt($cipher_alg, $keys, $str, MCRYPT_MODE_CBC,$iv));
        return $encrypted_string;
    }


    public static function postJsonForAes($url, $data,$keyStr, $JSON_UNESCAPED_UNICODE = false)
    {
        if ($JSON_UNESCAPED_UNICODE) {
            $data_string = json_encode($data, JSON_UNESCAPED_UNICODE);
        } else {
            $data_string = json_encode($data);
        }
        echo($data_string);
        echo('      ');

        //密钥
        $keyStr = 'xintai22eac4488ca3143chinalifecq';
        //加密的字符串

//        $dd = Tools::ecryptdString($data_string,'xintai22eac4488ca3143chinalifecq');

        $aes = new CryptAES();
        $aes->set_key($keyStr);
        $aes->require_pkcs5();
        $dd = $aes->encrypt($data_string);

        echo($dd);
        echo('      ');

//        $dd = Tools::ecryptdString($data_string);

        $x = ["message"=>$dd];

        if ($JSON_UNESCAPED_UNICODE) {
            $data_string = json_encode($x, JSON_UNESCAPED_UNICODE);
        } else {
            $data_string = json_encode($x);
        }

        echo($data_string);

        $ch = curl_init($url);
        //https 请求
        if (strlen($url) > 5 && strtolower(substr($url, 0, 5)) == 'https') {
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        }

        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                'Content-Type: application/json',
                'Content-Length: ' . strlen($data_string),
                'charset=utf-8',)

        );

        $result = curl_exec($ch);
        return $result;
    }

    public static function postForm($url, $data)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_USERAGENT, 'Opera/9.80 (Windows NT 6.2; Win64; x64) Presto/2.12.388 Version/12.15');
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); // stop verifying certificate
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_POST, true);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
        $result = curl_exec($curl);
        curl_close($curl);

        return $result;
    }

    /**
     * DES加密
     * @param $str
     * @param $key
     * @param $iv
     * @return string
     */
    public static function desEncode($str, $key, $iv)
    {
        $size = mcrypt_get_block_size(MCRYPT_DES, MCRYPT_MODE_CBC);
        $str = self::pkcs5Pad($str, $size);
        $aaa = mcrypt_cbc(MCRYPT_DES, $key, $str, MCRYPT_ENCRYPT, $iv);
        $ret = base64_encode($aaa);
        return $ret;
    }

    private static function pkcs5Pad($text, $blocksize)
    {
        $pad = $blocksize - (strlen($text) % $blocksize);
        return $text . str_repeat(chr($pad), $pad);
    }

    public static function uuid($prefix = '')
    {
        $chars = md5(uniqid(mt_rand(), true));
        $uuid = substr($chars, 0, 8) . '-';
        $uuid .= substr($chars, 8, 4) . '-';
        $uuid .= substr($chars, 12, 4) . '-';
        $uuid .= substr($chars, 16, 4) . '-';
        $uuid .= substr($chars, 20, 12);
        return $prefix . $uuid;
    }

    public static function db_uuid()
    {
        $cmd = \Yii::$app->db->createCommand("select uuid()");
        return $cmd->queryScalar();
    }

    public static function urlBase()
    {
        if (\Yii::$app->urlManager->showScriptName == true) {
            $url = \Yii::$app->request->scriptUrl;
        } else {
            $url = Url::base();
        }
        return $url;
    }

    /**
     * 获取系统主机地址
     * @return string
     */
    public static function urlIndex()
    {
        if (\Yii::$app->urlManager->showScriptName == true) {
            $url = \Yii::$app->request->getHostInfo() . \Yii::$app->request->getScriptUrl();
        } else {
            $url = \Yii::$app->request->getHostInfo() . \Yii::$app->request->getBaseUrl();
        }
        return $url;
    }

    public static function removeUrlParam($url, $paramName)
    {
        $t = explode('?', $url);
        $url = $t[0];
        if (count($t) > 1) {
            $pString = $t[1];
            if (count($pString) > 0) {
                $params = explode('&', $pString);
                $pCount = 0;
                foreach ($params as $param) {
                    $pName = explode('=', $param)[0];
                    if ($pName != $paramName) {
                        if ($pCount == 0) {
                            $url = $url . '?';
                        } else {
                            $url = $url . '&';
                        }
                        $pCount++;
                        $url = $url . $param;
                    }
                }
            }
        }

        return $url;
    }

    public static function var_dump_out($var)
    {
        ob_start();
        var_dump($var);
        $a = ob_get_contents();
        ob_end_clean();
        return $a;
        return htmlspecialchars($a, ENT_QUOTES); // Escape every HTML special chars (especially > and < )
    }

    /**
     * 获取随机字符串
     * @param $len
     * @param null $chars
     * @return string
     */
    public static function getRandomString($len, $chars = null)
    {
        if (is_null($chars)) {
            $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        }
        mt_srand(10000000 * (double)microtime());
        for ($i = 0, $str = '', $lc = strlen($chars) - 1; $i < $len; $i++) {
            $str .= $chars[mt_rand(0, $lc)];
        }
        return $str;
    }

    /**
     * @param \Exception $exception
     * @return string
     */
    public static function getExceptionFullTraceAsString($exception)
    {
        $rtn = "";
        try {
            $count = 0;
            foreach ($exception->getTrace() as $frame) {
                $args = "";
                if (isset($frame['args'])) {
                    $args = array();
                    foreach ($frame['args'] as $arg) {
                        if (is_string($arg)) {
                            $args[] = "'" . $arg . "'";
                        } elseif (is_array($arg)) {
                            $args[] = "Array";
                        } elseif (is_null($arg)) {
                            $args[] = 'NULL';
                        } elseif (is_bool($arg)) {
                            $args[] = ($arg) ? "true" : "false";
                        } elseif (is_object($arg)) {
                            $args[] = get_class($arg);
                        } elseif (is_resource($arg)) {
                            $args[] = get_resource_type($arg);
                        } else {
                            $args[] = $arg;
                        }
                    }
                    $args = join(", ", $args);
                }
                $current_file = "[internal function]";
                if (isset($frame['file'])) {
                    $current_file = $frame['file'];
                }
                $current_line = "";
                if (isset($frame['line'])) {
                    $current_line = $frame['line'];
                }
                $rtn .= sprintf("#%s %s(%s): %s(%s)\n",
                    $count,
                    $current_file,
                    $current_line,
                    $frame['function'],
                    $args);
                $count++;
            }
        } catch (\Exception $ex) {
            $rtn = $exception->getTraceAsString();
        }
        return $rtn;
    }

    /**
     * 转换日期函数
     * @param $datetime
     * @return false|string
     */
    public static function getConvertDate($datetime)
    {
        $datetime_str = '';
        try {
            $datetime_str = date('Y-m-d H:i:s', $datetime);
        } catch (\Exception $e) {
            $datetime_str = '';
        }
        return $datetime_str;
    }

    /**
     * pc-JD 分页列表转换
     * @param $currentPage  当前页
     * @param $totalPages   总页数
     * @param int $showPageRange  中间显示数目
     * @return array 输出分页对应的页码和省略号
     */

/*
 * 输出:array (size=10)
0 => string '1' (length=1)
1 => string 'preDot' (length=6)
2 => string '4' (length=1)
3 => string '5' (length=1)
4 => string '6' (length=1)
5 => string '7' (length=1)
6 => string '8' (length=1)
7 => string '9' (length=1)
8 => string 'lastDot' (length=7)
9 => string '12' (length=2)*/
    public static function getJDPageNumList($currentPage=1,$totalPages=1,$showPageRange=6){
//排除首页最后一页后显示的第一个超链接，最后一个超链接
        $startPage = 2;
        $endPage = $totalPages - 1;
//是否需要显示…对应的超链接
        $prevS = false;
        $nextS = false;

        if ($showPageRange + 4 < $totalPages) {//因为页面链接最多包含arg.showPageRange + 4个，所以如果总页数大于时，才显示对应的…

            $prevReduce = ($showPageRange / 2);
            $nextAdd = $prevReduce;
            if (($showPageRange % 2) == 0) {
                $prevReduce--;//showPageRange为偶数时，currentPage前面显示的页码链接数比后面显示的链接数少一个
            }
            if ($prevReduce < 0) {//修正当showPageRange被设置为1导致的负数
                $prevReduce = 0;
            }
            $startPage = $currentPage - $prevReduce;
            if ($startPage < 2) { $startPage = 2; }//修正startPage
            $endPage = $currentPage + $nextAdd;
            if ($endPage - $startPage < $showPageRange) { $endPage = $startPage + $showPageRange - 1; }//根据startPage修正endPage
            if ($endPage > $totalPages - 1) { $endPage = $totalPages - 1; $startPage = $endPage - $showPageRange + 1; }//修正endPage,并同步修正startPage
            if ($startPage <= 3) {//再次修正startPage
                $startPage = 2;
            }
            if ($endPage > $totalPages - 3) {//再次修正endPage
                $endPage = $totalPages - 1;
            }
            $prevS = $startPage - 1 > 1;
            $nextS = $endPage + 1 < $totalPages;

        }
        $pageList=[];


        $pageList[]='1';

        if ($prevS) {
            $pageList[]='preDot';//省略号
        }

        for ($i = $startPage; $i <= $endPage; $i++) {
            $pageList[]="$i";
        }
        if ($nextS) {
            $pageList[]='lastDot';//省略号
        }
        if ($totalPages > 1) {
            $pageList[]= $totalPages;
        }
//        var_dump($pageList);
        return $pageList;
    }
}